<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />
    <van-form @submit="login">
      <van-field
        :rules="rules.mobile"
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
      />
      <van-field
        :rules="rules.code"
        v-model="code"
        required
        label="验证码"
        placeholder="请输入验证码"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="loading"
          :disabled="loading"
          loading-text="登录中..."
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// import request from '@/utils/request'
import { login } from '@/api/user'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '13912345678',
      code: '246810',
      loading: false,
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    // 1.原方法，未封装
    // login() {
    //   request({
    //     method: 'POST',
    //     url: '/v1_0/authorizations',
    //     data: {
    //       mobile: this.mobile,
    //       code: this.code
    //     }
    //   })
    //     .then(res => {
    //       console.log(res)
    //       this.$toast.success('登录成功')
    //       this.$router.push('/')
    //     })
    //     .catch(err => {
    //       console.log(err)
    //       this.$toast.fail('登录失败')
    //     })
    // }
    // 2.封装后
    // ...mapMutations('user', ['setToken']),
    async login() {
      this.loading = true
      // await只会等待promise成功的结果，如果promise失败，await会直接报错
      try {
        const res = await login(this.mobile, this.code)
        this.$store.commit('user/setToken', res.data)
        this.$toast.success('登录成功')
        let back = this.$route.query.back
        if (back === 'true') {
          this.$router.back()
        } else {
          back = back || '/'
          this.$router.push(back)
        }
      } catch {
        this.$toast.fail('登录失败')
      }
      this.loading = false
    }
  }
}
</script>

<style></style>
